/**
 * @author [siwi]
 * @email [siwi@siwi.me]
 * @create date 2017-05-26 03:53:05
 * @modify date 2017-05-26 03:53:05
 * @desc [database connect]
*/

const Conf = require('./config')
const mongoose = require('mongoose')
mongoose.Promise = Promise
module.exports.connect = () => {
  return new Promise((resolve, reject) => {
    let url = process.env.MONGODB_URI || Conf.mongodbUri
    let conn = mongoose.connection
    conn.on('error', (err) => reject(err))
    conn.once('open', () => {
      console.log(`the mongodb is connection at ${url}`)
      resolve()
    })
    conn.on('disconnected', () => {
      console.log('mongodb the connection is closed')
    })
    process.on('SIGINT', () => {
      conn.close(() => {
        console.log('mongodb the connect is closed ')
        process.exit(0)
      })
    })
    mongoose.connect(url)
  })
}
module.exports.plugin = (schame) => {
  schame.add({
    created: {
      type: Date,
      default: new Date

    },
    updated: {
      type: Date,
      default: new Date()
    }
  })

  // 这路不能使用箭头函数

  schame.pre('save', (next) => {
    if (!this.created) {
      this.created = new Date()
    }
    this.updated = new Date()
    next()
  })
  if (!schame.options.toObject) {
    schame.options.toObject = {}
  }
  if (!schame.options.toJSON) {
    schame.options.toJSON = {}
  }

  /**
   * 转换
   * @param {*} doc 
   * @param {*} ret 
   * @param {*} options 
   */
  const transform = (doc, ret, options) => {
    ret.id = ret._id
    delete ret.__v
    delete ret._id
    return ret
  }
  schame.options.toObject.transform = transform
  schame.options.toJSON.transform = transform
}
